import logging
import uuid
import os
import pymysql
import base64
import datetime
from django.http import JsonResponse, StreamingHttpResponse
from comment.comviews import com_views, success_response, err_response, format_response
from utils.dbutils import PymysqlUtil, DB_Config, MysqlTools
from utils.formatutils import get_params
from .sqlmap import *
from django.db import connection

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))



def upload_img(params):
    dict = {
        "img_base64": "img_base64",
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if not val:
    #         return err_response(210)
    list = params["img_base64"].split(";")
    shuffix = list[0][5:].split("/")[1]
    filename = str(uuid.uuid4()).replace("-", "") + "." + shuffix
    params["img_name"] = filename
    with open("/home/oasys/img/%s" % (filename), "wb") as f:
        base64_data = base64.b64decode(list[1][7:])
        size = len(base64_data)
        f.write(base64_data)
    logging.info("upload_img:{}".format(params.get("img_name")))
    user_name = mysql_tools.select_one(UserSqlMap.CHECK_USER_NAME.format(**params))
    year = str(datetime.datetime.now())[0:4]
    month = str(datetime.datetime.now())[5:7]
    user_name = user_name["user_name"]
    params["attachment_path"] = "/" + year + "/" + month + "/" + user_name + "/" + filename
    params["attachment_shuffix"] = shuffix
    params["attachment_size"] = size
    params["attachment_type"] = list[0][5:]
    params["model"] = "image"
    path = "/home/oasys/attachment/" + year + "/" + month + "/" + user_name
    if not os.path.exists(path):       # 判断文件夹是否存在
        os.makedirs(path)                 # 创建文件夹
    with open("/home/oasys/attachment%s" % (params["attachment_path"]), "wb") as f:
        base64_data = base64.b64decode(list[1][7:])
        f.write(base64_data)
    sql = UserSqlMap.INSERT_ATTACHMENT.format(**params)
    mysql_tools.execute_sql(sql)
    attach_id = mysql_tools.select_one(UserSqlMap.GET_ID).get("id")
    result = {
        "img_name": "static/img/{}".format(params["img_name"]),
        "attach_id": attach_id
    }
    return success_response(result)


@format_response
def index(request):
    return com_views(request, {
        "upload_img": upload_img
    })
